-- UIUnlockRoom
-- Create by zouyb
-- 解锁界面

--UIUnlockRoom继承自Layer
UIUnlockRoom = class("UIUnlockRoom", function()
    return cc.Layer:create();
end);

function UIUnlockRoom.create()
    return UIUnlockRoom.new();
end

local resize;

--构造函数
function UIUnlockRoom:ctor()
    self:setName("UIUnlockRoom");

    --初始化
    local node = cc.CSLoader:createNode("layout/workshop/StrengthenDetail.csb");
    self:addChild(node);
    self.node = node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIUnlockRoom");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册强化按钮点击事件
    local btnBuy = findChildByName(self.node, "CT/strengthen");
    local function onBuyClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            -- 金币是否足够
            local curMoney = ME.user.dbase:query("money", 0);
            local price = FormulaM.invoke("CALC_UNLOCK_TRAINING_ROOM_COST", ME.user);
            if     curMoney < price[1][3] then
                alert(getLocStr("money_lack"));
                return;
            end

            -- 通知服务器解锁
            Operation.cmd_unlock_training_room();

            UIMgr.getCurrentScene():removeFormByName("UIUnlockRoom");

            -- 播放升级特效
            local uiForm = UIMgr.getCurrentScene():getFormByName("UITalentMain");
            uiForm:showTrainingRoomUpgradeEffect();
        end
    end
    btnBuy:addTouchEventListener(onBuyClick);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBuy:setTitleText(getLocStr("btn_text_build"));

    self.costParentNode = findChildByName(self.node, "CT/cost");
    self.originCostParentPosX = self.costParentNode:getPositionX();
    self.originCostParentPosY = self.costParentNode:getPositionY();

    self:redraw();    
    -- 调整高度
    self:adjustHeight();

    resize(self);

    -- 注册获得焦点的回调
    EventMgr.register("UIUnlockRoom", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIUnlockRoom" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_FRUIT);
        end
    end);

    -- 金币值更新回调
    ME.user.dbase:registerCb("UIUnlockRoom", { "money", }, function()
        self:redraw();
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIUnlockRoom界面析构清理");

            -- 移除所有事件回调
            EventMgr.removeAll("UIUnlockRoom");
            ME.user.dbase:removeCb("UIUnlockRoom", { "money", });

        elseif ev == "enter" then

        end
    end);
end

-- 界面重绘
function UIUnlockRoom:redraw()
    -- 标题
    local titleLabel = findChildByName(self.node, "CT/template/title");
    titleLabel:setString(getLocStr("training_room"));
    TextStyleM.setTitleStyle(titleLabel);

    -- 道具描述1
    local desc1Label = findChildByName(self.node, "CT/desc1");
    TextStyleM.setTextStyle(desc1Label,TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(desc1Label, getLocStr("build_training_room_desc"));

    -- 图标
    local item = findChildByName(self.node, "CT/item");
    local icon = item:getChildByName("icon");
    icon:loadTexture("images/item/7125.png");

    local frame = item:getChildByName("frame");
    frame:loadTexture("images/ui/frame/frame_hero_upgrade.png");

    -- 等级
    local levelLabel = item:getChildByName("level");
    levelLabel:setVisible(false);

    -- 花费
    self:initCost();
end

-- 花费金币
function UIUnlockRoom:initCost()
    local costLabel = findChildByName(self.node, "CT/cost");
    TextStyleM.setTextStyle(costLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, false);
    costLabel:getVirtualRenderer():setLineHeight(TextStyleM.TEXT_SIZE_SMALL + 5);

    local cost = FormulaM.invoke("CALC_UNLOCK_TRAINING_ROOM_COST", ME.user);

    local index = 0;
    local costStr = "";
    for _, arr in pairs(cost) do
        index = index + 1;

        local name, nameStr;
        local needNum = arr[3];
        local curNum;
        if arr[1] == 1 then
            name = ItemM.query(arr[2], "name");
            nameStr = string.format(getLocStr("need_item_amount"), name, needNum);
            curNum = ItemM.getAmount(ME.user, arr[2]);
        elseif arr[1] == 2 then
            name = FieldsM.getFieldName(arr[2]);
            nameStr = string.format(getLocStr("need_money_amount"), name, needNum);
            curNum = ME.user:queryAttrib(arr[2]);
        end

        if curNum >= needNum then
            nameStr = string.gsub(nameStr, "{0}", "blue");
        else
            nameStr = string.gsub(nameStr, "{0}", "red");
        end        

        local amountStr;
        if arr[1] == 2 then
            -- 金币
            amountStr = "";
        else
            -- 材料
            amountStr = string.format(getLocStr("current_amount"), curNum);
        end

        costStr = costStr .. nameStr .. " " .. amountStr .. "\n";
    end

    applyString(costLabel, costStr);
end

-- 调整高度
function UIUnlockRoom:adjustHeight()
    local costLabel = findChildByName(self.node, "CT/cost");
    local lineNum = costLabel:getVirtualRenderer():getStringNumLines();

    local delta = (3 - lineNum) * TextStyleM.TEXT_SIZE_SMALL;
    if delta == 0 then
        return;
    end

    costLabel:setPositionY(costLabel:getPositionY() + delta / 2);

    local btnBuy = findChildByName(self.node, "CT/strengthen");
    btnBuy:setPositionY(btnBuy:getPositionY() + delta);

    local bg = findChildByName(self.node, "CT/template/bg");

    local bgDelta = delta / bg:getScaleY();
    local bg3 = findChildByName(self.node, "CT/template/bg/bg3");
    bg3:setPositionY(bg3:getPositionY() + bgDelta );
    local bg4 = findChildByName(self.node, "CT/template/bg/bg4");
    bg4:setPositionY(bg4:getPositionY() + bgDelta);
end

resize = function(self)
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end


